module.exports = app => {
    return class OrderService extends app.Service {
        async createOrder() {
            let app = this.app;
            let ctx = this.ctx;
            let token = ctx.params.token;
            let carts = ctx.params.carts;
            try {
                carts = JSON.parse(carts);
            } catch (e) {

            }
            if (!token) {
                return {
                    msg: '缺少token'
                };
            }
            if (!carts || (carts && carts.length === 0)) {
                return {
                    msg: '缺少购物车或购物车为空'
                };
            }

            // 根据id把响应的food找出来
            let cartsIds = [];
            for (let entry of carts) {
                cartsIds.push(entry.id);
            }
            let resultSet = await app.mongo.find('foods', {
                query: {
                    item_id: {
                        '$in': cartsIds
                    }
                }
            })
            // 给每个传过来的商品加入商品详情
            for (let [index, cart] of carts.entries()) {
                // entry商品详情
                let entry = resultSet.find(item => {
                    return item.item_id = cart.id;
                })
                carts[index] = {
                    ...cart,
                    ...entry
                }
            }
            // 计算商品的总价和有几种商品
            let foodName = '';
            let totalMoney = 0;
            for (let cart of carts) {
                foodName += cart.name + '+';;
                totalMoney += cart.specfoods[0].price * cart.buyNum
            }
            foodName = foodName.slice(0, -1);
            totalMoney = totalMoney.toFixed(2);
            let doc = {
                foodName,
                totalMoney,
                carts,
                createTime: app.utils.formatDate(new Date()),
                userId: token
            }
            let inserResult = await app.mongo.insertOne('orders', {
                doc
            });
            if (inserResult.insertedCount > 0) {
                // 清空购物车
                app.mongo.deleteMany('carts', {
                    filter: {}
                });
                return {
                    code: 0,
                    msg: '订单创建成功'
                }
            } else {
                return {
                    msg: '订单创建失败'
                }
            }

        }

        async delOrder() {
            return 'del';
        }

        async orderList() {
            let mongo = this.app.mongo;
            let token = this.ctx.params.token;
            if (!token) {
                return {
                    msg: '缺少token'
                }
            }
            let res = await mongo.find('orders');
            return {
                code: 0,
                msg: 'success',
                list: res
            }
        }
    }
}